package javax.per.toolkit.search;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.per.toolkit.file.FileUtil;
import javax.per.toolkit.tools.Fun;
import javax.per.toolkit.tools.Log;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import tools.Env;

public class ffs {
	
	private static List<String> notContainType=new ArrayList<String>();
	private static IndexWriter iWriter=null;
	
	static{
		notContainType.add("jar".toUpperCase());
		notContainType.add("class".toUpperCase());
		notContainType.add("gif".toUpperCase());
		notContainType.add("jpg".toUpperCase());
		notContainType.add("pdf".toUpperCase());
		notContainType.add("bmp".toUpperCase());
	}
	
	public static void main(String[] args){
		for(String str:args){
			if(str.equalsIgnoreCase("-update")){
				try {
					pre();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return;
			}
		}
		try {
			String str=Fun.getConsoleString();
			String filepath=Env.get("tempFileDir").replaceAll("\\\\", "/")+"/fs";
			if(!new File(filepath).exists()){
				Log.getLogger().debug("update index...");
				pre();
			}
			Directory dir=FSDirectory.open(new File(filepath));
			DirectoryReader dReader=DirectoryReader.open(dir);
			IndexSearcher iSearcher=new IndexSearcher(dReader);
			@SuppressWarnings("deprecation")
			Analyzer analyser=new StandardAnalyzer(Version.LUCENE_CURRENT);
			@SuppressWarnings("deprecation")
			QueryParser qParser=new QueryParser(Version.LUCENE_CURRENT,"fieldName",analyser);
			Query query=qParser.parse(str);
			ScoreDoc[] hits=iSearcher.search(query, null,1000).scoreDocs;
			System.out.println(hits.length);
			for(ScoreDoc hit:hits){
				System.out.println(iSearcher.doc(hit.doc).get("path"));
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
	
	public static void pre() throws IOException{
		String str=Env.get("FileSearchDir");
		String[] dirs=str.split(";");
		@SuppressWarnings("deprecation")
		Analyzer analyser=new StandardAnalyzer(Version.LUCENE_CURRENT);
		@SuppressWarnings("deprecation")
		IndexWriterConfig config=new IndexWriterConfig(Version.LUCENE_CURRENT,analyser);
		Directory dir=FSDirectory.open(new File(Env.get("tempFileDir").replaceAll("\\\\", "/")+"/fs"));
		iWriter=new IndexWriter(dir,config);
		for(String d:dirs){
			loop(new File(d));
		}
		iWriter.close();
	}
	
	private static void loop(File f) throws IOException{
		if(f.isDirectory()){
			for(File fs:f.listFiles()){
				loop(fs);
			}
		}else{
			String ext=FileUtil.getExtension(f.getAbsolutePath()).toUpperCase();
			if(notContainType.contains(ext))
				return;
			Document doc=new Document();
			doc.add(new StringField("path",f.getAbsolutePath(),Field.Store.YES));
			try{
			doc.add(new TextField("content",FileUtil.getReader(f.getAbsolutePath())));
			}catch(Exception e){
				Fun.pl(f.getAbsolutePath());
				e.printStackTrace();
			}
			iWriter.updateDocument(new Term("path",f.getAbsolutePath()), doc);
		}
	}
}
